<template>
  <div class="footer">
    <div class="footer-left">
      <el-button 
        type="text" 
        @click="showHistory = true"
        class="history-btn"
      >
        <el-icon><Clock /></el-icon>
        历史生成记录
      </el-button>
      <span class="status-text">准备生成数据...</span>
    </div>
    
    <div class="footer-right">
      <el-button
        type="success"
        size="large"
        @click="generateData"
        :loading="generating"
        class="generate-btn"
      >
        <el-icon><Download /></el-icon>
        生成测试数据
      </el-button>
    </div>

    <!-- 历史记录对话框 -->
    <el-dialog
      v-model="showHistory"
      title="历史生成记录"
      width="800px"
      :before-close="handleCloseHistory"
    >
      <div v-if="history.length === 0" class="empty-history">
        <el-empty description="暂无历史记录" />
      </div>
      <div v-else>
        <el-table :data="history" style="width: 100%" max-height="400">
          <el-table-column prop="timestamp" label="生成时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.timestamp) }}
            </template>
          </el-table-column>
          <el-table-column prop="dataCount" label="数据量" width="100">
            <template #default="{ row }">
              {{ row.dataCount.toLocaleString() }} 条
            </template>
          </el-table-column>
          <el-table-column prop="fieldCount" label="字段数" width="80">
            <template #default="{ row }">
              {{ row.fieldCount }} 个
            </template>
          </el-table-column>
          <el-table-column prop="fileFormat" label="格式" width="100" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 'completed' ? 'success' : 'warning'"
              >
                {{ row.status === 'completed' ? '已完成' : '生成中' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="downloadFile(row)"
                :disabled="row.status !== 'completed'"
              >
                下载
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="deleteRecord(row)"
                style="color: #f56c6c"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 生成进度对话框 -->
    <el-dialog
      v-model="showProgress"
      title="正在生成数据"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="progress-content">
        <el-progress
          :percentage="progress"
          :stroke-width="8"
          :show-text="true"
        />
        <p class="progress-text">{{ progressText }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Clock, Download } from '@element-plus/icons-vue'

export default {
  name: 'Footer',
  components: {
    Clock,
    Download
  },
  setup() {
    const store = useStore()
    const showHistory = ref(false)
    const showProgress = ref(false)
    const generating = ref(false)
    const progress = ref(0)
    const progressText = ref('')
    
    const history = computed(() => store.state.history)
    const dataCount = computed(() => store.state.dataCount)
    const fields = computed(() => store.state.fields)
    const fileFormat = computed(() => store.state.fileFormat)
    
    const formatTime = (timestamp) => {
      return new Date(timestamp).toLocaleString('zh-CN')
    }
    
    const generateData = async () => {
      if (fields.value.length === 0) {
        ElMessage.warning('请至少添加一个字段')
        return
      }
      
      generating.value = true
      showProgress.value = true
      progress.value = 0
      progressText.value = '开始生成数据...'
      
      try {
        // 模拟数据生成过程
        const steps = [
          { text: '验证字段配置...', duration: 500 },
          { text: '初始化数据生成器...', duration: 800 },
          { text: '生成数据记录...', duration: 2000 },
          { text: '格式化输出文件...', duration: 700 },
          { text: '完成数据生成', duration: 300 }
        ]
        
        let totalProgress = 0
        const stepProgress = 100 / steps.length
        
        for (const step of steps) {
          progressText.value = step.text
          await new Promise(resolve => setTimeout(resolve, step.duration))
          totalProgress += stepProgress
          progress.value = Math.min(100, totalProgress)
        }
        
        // 添加到历史记录
        const record = {
          dataCount: dataCount.value,
          fieldCount: fields.value.length,
          fileFormat: fileFormat.value,
          status: 'completed',
          fileName: `test_data_${Date.now()}.${fileFormat.value.toLowerCase().replace('格式', '')}`
        }
        
        store.dispatch('addHistory', record)
        
        ElMessage.success('数据生成完成！')
        
        // 模拟文件下载
        setTimeout(() => {
          const link = document.createElement('a')
          link.download = record.fileName
          link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(
            `# 测试数据文件\n生成时间: ${new Date().toLocaleString()}\n数据量: ${dataCount.value} 条\n字段数: ${fields.value.length} 个\n\n# 这是一个示例文件`
          )
          link.click()
        }, 1000)
        
      } catch (error) {
        ElMessage.error('数据生成失败：' + error.message)
      } finally {
        generating.value = false
        showProgress.value = false
        progress.value = 0
      }
    }
    
    const downloadFile = (record) => {
      // 模拟文件下载
      const link = document.createElement('a')
      link.download = record.fileName
      link.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(
        `# 测试数据文件\n生成时间: ${formatTime(record.timestamp)}\n数据量: ${record.dataCount} 条\n字段数: ${record.fieldCount} 个\n\n# 这是一个示例文件`
      )
      link.click()
      ElMessage.success('文件下载已开始')
    }
    
    const deleteRecord = (record) => {
      // 从历史记录中删除
      const index = history.value.findIndex(item => item.id === record.id)
      if (index > -1) {
        store.state.history.splice(index, 1)
        ElMessage.success('记录已删除')
      }
    }
    
    const handleCloseHistory = () => {
      showHistory.value = false
    }
    
    return {
      showHistory,
      showProgress,
      generating,
      progress,
      progressText,
      history,
      formatTime,
      generateData,
      downloadFile,
      deleteRecord,
      handleCloseHistory
    }
  }
}
</script>

<style scoped>
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
  flex-shrink: 0;
  gap: 16px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
  min-width: 0;
}

.footer-right {
  flex-shrink: 0;
}

.history-btn {
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}

.status-text {
  color: #999;
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.generate-btn {
  height: 40px;
  padding: 0 24px;
  font-size: 14px;
  border-radius: 6px;
  white-space: nowrap;
}

.empty-history {
  text-align: center;
  padding: 40px 0;
}

.progress-content {
  text-align: center;
  padding: 20px 0;
}

.progress-text {
  margin-top: 16px;
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .footer {
    flex-direction: column;
    gap: 12px;
    padding: 16px;
  }
  
  .footer-left {
    justify-content: center;
    width: 100%;
    flex-direction: column;
    gap: 8px;
  }
  
  .footer-right {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  
  .generate-btn {
    width: 100%;
    max-width: 300px;
  }
}

@media (max-width: 480px) {
  .footer-left {
    gap: 4px;
  }
  
  .status-text {
    font-size: 12px;
  }
}
</style>